<template>
  <div>
    <el-button type="primary" icon="el-icon-plus" @click="addDialog"
      >添加</el-button
    >
    <el-table style="width: 100%" :data="tradeMarkList">
      <el-table-column type="index" label="序号" width="80px" />
      <el-table-column prop="tmName" label="品牌名称" width="width" />
      <el-table-column prop="logoUrl" label="品牌LOGO" width="width">
        <template slot-scope="{ row }">
          <img :src="row.logoUrl" style="height: 100px; width: 100px" />
        </template>
      </el-table-column>

      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="{ row }">
          <el-button
            type="warning"
            size="mini"
            icon="el-icon-edit"
            @click="updateDialog(row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="deleteTradeMark(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 20px; textalign: center"
      :current-page="page"
      :page-sizes="[3, 5, 10]"
      :page-size="limit"
      :page-count="7"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @size-change="sizeChange"
      @current-change="currentChange"
    />
    <!-- 对话框 -->
    <el-dialog
      :title="this.tmInfo ? '修改品牌' : '添加品牌'"
      :visible.sync="dialogFormVisible"
      @close="dialogClose"
    >
      <el-form style="width: 80%" :model="tmInfo" :rules="rules" ref="rulesRef">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input autocomplete="off" v-model="tmInfo.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmInfo.logoUrl" :src="tmInfo.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'TradeMark',
  data() {
    return {
      // 当前是第几页
      page: 1,
      // 当页数据条数
      limit: 3,
      // 总数据条数
      total: 0,
      // 数据列表
      tradeMarkList: [],
      // 对话框显示与隐藏
      dialogFormVisible: false,
      // 收集对象上的信息
      tmInfo: {
        tmName: '',
        logoUrl: ''
      },
      // 表单验证规则
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        logoUrl: [
          { required: true, message: '请选择品牌LOGO', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.getTradeMarkList()
  },
  methods: {
    //请求数据
    async getTradeMarkList() {
      const { page, limit } = this
      const result = await this.$API.tradeMark.reqTradeMarkList(page, limit)
      console.log(result)
      if (result.code === 200) {
        this.total = result.data.total
        this.tradeMarkList = result.data.records
      }
    },
    //PageSize改变时触发
    sizeChange(page) {
      this.limit = page
      this.getTradeMarkList()
    },
    //currentPage改变时触发
    currentChange(page) {
      this.page = page
      this.getTradeMarkList()
    },
    //显示对话框
    addDialog() {
      /* this.tmInfo = { tmName: '', logoUrl: '' } */
      this.dialogFormVisible = true
    },
    //修改对话框
    updateDialog(row) {
      this.dialogFormVisible = true
      this.tmInfo = { ...row }
    },
    //图片上传成功的回调
    handleAvatarSuccess(res, file) {
      this.tmInfo.logoUrl = res.data
    },
    //图片上传前的回调
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 添加或更新品牌
    addOrUpdateTradeMark() {
      this.$refs.rulesRef.validate(async (valid) => {
        if (valid) {
          this.dialogFormVisible = false
          const result = await this.$API.tradeMark.reqAddOrUpdateTradeMark(
            this.tmInfo
          )
          if (result.code == 200) {
            this.$message.success(
              this.tmInfo.id ? '品牌修改成功' : '品牌添加成功'
            )
            this.currentChange(this.tmInfo.id ? this.page : 1)
            this.getTradeMarkList()
          } else {
            this.$message.error(
              this.tmInfo.id ? '品牌修改失败' : '品牌添加失败'
            )
          }
        } else {
          return false
        }
      })
    },
    //关闭对话框时对该表单项进行重置，将其值重置为初始值并移除校验结果
    dialogClose() {
      this.$refs.rulesRef.resetFields()
    },
    //删除品牌的操作
    deleteTradeMark(row) {
      //弹框
      this.$confirm(`你确定删除${row.tmName}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          //当用户点击确定按钮的时候会出发
          //向服务器发请求
          let result = await this.$API.tradeMark.reqDeleteTradeMark(row.id)
          //如果删除成功
          console.log(result)
          if (result.code == 200) {
            this.$message.success('删除成功!')
            //再次获取品牌列表数据
            //当页只有一条数据则跳转至上一页
            this.currentChange(
              this.tradeMarkList.length > 1 ? this.page : this.page - 1
            )
            this.getTradeMarkList()
          }
        })
        .catch(() => {
          //当用户点击取消按钮的时候会触发
          this.$message('已取消删除')
        })
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
